package com.yili99.springmvc.crud.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Repository;

import com.yili99.springmvc.crud.entities.SanguisIndex;
import com.yili99.springmvc.crud.entities.SanguisIndex2;

@Repository
public class SanguisIndexDao {

	public Collection<SanguisIndex> getAll() {

		System.out.println("test...");

		SessionFactory sessionFactory = null;

		Configuration configuration = new Configuration().configure();

		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		Session session = sessionFactory.openSession();

		Transaction transaction = session.beginTransaction();

		String hql = "FROM SanguisIndex";
		Query query = session.createQuery(hql);  
        List<SanguisIndex> sanguisIndexList = query.list();  

		transaction.commit();

		session.close();

		sessionFactory.close();
		return sanguisIndexList;
	}
	
	public void insert(SanguisIndex2 sanguisIndex) {
		SessionFactory sessionFactory = null;

		Configuration configuration = new Configuration().configure();

		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		Session session = sessionFactory.openSession();


		Transaction transaction = session.beginTransaction();

		session.save(sanguisIndex);

		transaction.commit();

		session.close();

		sessionFactory.close();
	}
}
